package com.entor.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.entor.entity.User;
import org.entor.util.HandleCookie;

import com.entor.sql.UserDaoImpl;

public class Login extends HttpServlet{

	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String name = req.getParameter("uname");
		String password = req.getParameter("upwd");
		UserDaoImpl udi = new UserDaoImpl();
		User user = new User(name, password);
		System.out.println(user);
		boolean flag = false;
//		HandleCookie.loginState(req);
//		判断用户名密码是否匹配
		int stat = udi.isuser(user);
//		System.out.println(stat+"怎么会这样");
		if(stat!=-1){
//			System.out.println(stat);
			flag=true;
//			使用session保存登录状态和用户名
			HttpSession session = req.getSession();
			session.setAttribute("flag", flag);
//			session.setAttribute("uname", name);
			Cookie cookieuid = new Cookie("uid", stat+"");
			Cookie cookieuname = new Cookie("uname", name);
			req.setAttribute("uname", name);
//			System.out.println(stat);
//			设置cookie有效期为一天
			cookieuid.setMaxAge(86400);
			cookieuid.setPath(req.getContextPath());
			cookieuname.setMaxAge(86400);
			cookieuname.setPath(req.getContextPath());
			resp.addCookie(cookieuid);
			resp.addCookie(cookieuname);
//			System.out.println(stat+"741852");
//			resp.sendRedirect("../newspages/admin.jsp");
			
			resp.sendRedirect("../newspages/admin.jsp");;
			
//			System.out.println(stat);
		}else{
			req.setAttribute("flag", flag);
//			System.out.println(req.getHeader("Referer"));
			resp.sendRedirect("../index.jsp");
		}
	}
	
//	登录时拒绝get请求
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("utf-8");
		PrintWriter pw = resp.getWriter();
		pw.println("错误");
		pw.flush();
		pw.close();
	}
}
